<?php

declare(strict_types=1);

namespace App\CustHub\Request;

use App\CustHub\Service\ChUserService;
use App\System\Model\SystemUser;
use Mine\MineFormRequest;

class SubUserRequest extends MineFormRequest
{
    public function saveRules()
    {
        return [
            'username' => 'required|max:120',
            'account' => 'required|max:120',
            'password' => 'required|max:20',
            'seat_quota' => 'required|integer|min:-1',
            'expire_time' => 'required',
            'role_id' => 'required',
            'data_scope' => 'required|in:0,1,2',
            'data_scope_allow' => 'in:0,1'
        ];
    }

    public function updateRules()
    {
        $saveRules = $this->saveRules();
        unset($saveRules['password']);
        return array_merge( [
            'id' => 'required',
        ], $saveRules);
    }

    public function getInfoRules()
    {
        return [
            'id' => 'required'
        ];
    }

    public function deleteRules()
    {
        return [
            'id' => 'required'
        ];
    }

    public function setGroupRules()
    {
        return [
            'ids' => 'required',
            'group_id' => 'required'
        ];
    }

    /**
     * 修改密码验证规则
     * return array.
     */
    public function modifyPasswordRules(): array
    {
        return [
            'newPassword' => 'required|confirmed|string',
            'newPassword_confirmation' => 'required|string',
            'oldPassword' => ['required', function ($attribute, $value, $fail) {
                $service = $this->container->get(ChUserService::class);
                /**
                 * @var SystemUser $model
                 */
                $model = $service->mapper->getModel()::find((int) chUser()->getId(), ['password']);
                if (! $service->mapper->checkPass($value, $model->password)) {
                    $fail(t('system.valid_password'));
                }
            }],
        ];
    }
}